package com.kexuexiong.demo.bear.controller.es;

import cn.hutool.core.util.RandomUtil;
import com.kexuexiong.demo.bear.common.dto.Result;
import com.kexuexiong.demo.bear.controller.BaseController;
import com.kexuexiong.demo.bear.elasticsearch.dto.ESSearchDTO;
import com.kexuexiong.demo.bear.elasticsearch.model.Person;
import com.kexuexiong.demo.bear.elasticsearch.model.Sougoulog;
import com.kexuexiong.demo.bear.elasticsearch.repository.EsSougouDao;
import com.kexuexiong.demo.bear.elasticsearch.repository.PersonDao;
import com.kexuexiong.demo.bear.elasticsearch.service.EsPersonService;
import com.kexuexiong.demo.bear.elasticsearch.service.EsSougouService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

@RestController
@RequestMapping("/api/es/")
@Api(tags = {"搜索引擎"})
@Slf4j
public class EsController extends BaseController {

    @Autowired
    private PersonDao personDao;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    private EsPersonService esPersonService;

    @Autowired
    private EsSougouDao esSougouDao;

    @Autowired
    private EsSougouService esSougouService;

    /**
     * es测试
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/esImportDate", method = {RequestMethod.GET})
    @ApiOperation(value = "esImportDate", notes = "搜索引擎es导入数据")
    public Result<String> esImportDate() {
        List<Person> personList = new LinkedList<>();

        for (int i = 0; i < 10000; i++) {
            Person person = new Person();
            person.setId(RandomUtil.randomNumbers(8));
            person.setPassword(RandomUtil.randomNumbers(5));
            person.setUserName("keuxexiong" + RandomUtil.randomNumbers(8));
            person.setRoles(Arrays.asList("admin"));
            person.setContent(RandomUtil.randomNumbers(8) + "parameter is deprecated because frozen indices have been deprecated. Consider cold or frozen tiers in place of frozen indices");
            person.setLevel(5);
            personList.add(person);
        }
        try {
            personDao.saveAll(personList);
        } catch (Exception e) {
            if (e.getMessage().contains("OK")) {
                //DO nothing
                log.warn("es导入数据：{}", e.getMessage());
                return Result.success();
            } else {
                throw new RuntimeException(e.getMessage());
            }
        }
        return Result.success();
    }

    /**
     * es根据名字查询
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/esSearchByName", method = {RequestMethod.GET})
    @ApiOperation(value = "esSearchByName", notes = "搜索引擎es根据名字查询")
    public Result<Object> esSearchByName(@Parameter(name = "name", required = false) @RequestParam(value = "name", required = false) String name,
                                         @Parameter(name = "content") @RequestParam("content") String content) {
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
//        nativeSearchQueryBuilder.withQuery(QueryBuilders.matchQuery("userName",name));
        nativeSearchQueryBuilder.withQuery(QueryBuilders.matchQuery("content", content));
        nativeSearchQueryBuilder.withPageable(PageRequest.of(0, 10));
        NativeSearchQuery build = nativeSearchQueryBuilder.build();
        build.addFields("userName", "password", "roles", "content");
        SearchHits<Person> search = elasticsearchRestTemplate.search(build, Person.class);
        return Result.success(search);
    }

    /**
     * es根据名字查询
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/esSearchDeletedAll", method = {RequestMethod.GET})
    @ApiOperation(value = "esSearchDeletedAll", notes = "搜索引擎es删除所有")
    public Result<Object> esSearchDeletedAll() {
        personDao.deleteAll();
        return Result.success();
    }


    /**
     * es根据名字查询高亮
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/esSearchHighlight", method = {RequestMethod.GET})
    @ApiOperation(value = "esSearchHighlight", notes = "搜索引擎es根据名字高亮查询")
    public Result<Object> esSearchHighlight(@Parameter(name = "name", required = false) @RequestParam(value = "name", required = false) String name,
                                            @Parameter(name = "content") @RequestParam("content") String content) {
        SearchHits<Person> search = esPersonService.searchPerson(content, 0, 10);
        return Result.success(search);
    }

    /**
     * es根据名字查询高亮
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/esSearchLogHighlight", method = {RequestMethod.POST})
    @ApiOperation(value = "esSearchLogHighlight", notes = "log搜索引擎es根据高亮查询")
    public Result<Object> esSearchLogHighlight(@Parameter(name = "esSearchDTO", required = true) @RequestBody ESSearchDTO esSearchDTO) {
        SearchHits<Sougoulog> search = esSougouService.search(esSearchDTO);
        return Result.success(search);
    }

    /**
     * es测试 sougou log 数据导入
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/esSouGouLogImportDate", method = {RequestMethod.GET})
    @ApiOperation(value = "esSouGouLogImportDate", notes = "sougou搜索引擎es导入数据")
    public Result<String> esSouGouLogImportDate() throws Exception {
        BufferedReader br = new BufferedReader(new FileReader(ResourceUtils.getFile("classpath:SougouQ.log")));
        String s;
        Integer i = 1;
        List<Sougoulog> jsonDocs = new ArrayList<>();
        while ((s = br.readLine()) != null) {
            String[] words = s.split(" |\t");
            System.out.println(words[0] + " " + words[1] + words[2] + words[5]);
            Sougoulog log = new Sougoulog();
            log.setId(i.toString());
            log.setVisittime(words[0]);
            log.setUserid(words[1]);
            log.setKeywords(words[2]);
            log.setRank(Integer.parseInt(words[3]));
            log.setClicknum(Integer.parseInt(words[4]));
            log.setUrl(words[5]);
            jsonDocs.add(log);
            i++;
        }
        try {
            esSougouDao.saveAll(jsonDocs);
        } catch (Exception e) {
            if (e.getMessage().contains("OK")) {
                //DO nothing
                log.warn("es导入数据：{}", e.getMessage());
                return Result.success();
            } else {
                throw new RuntimeException(e.getMessage());
            }
        }
        return Result.success();
    }
}
